package com.durian.utils;

import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.durian.config.ServiceException;
import org.springframework.beans.BeanUtils;

import java.lang.reflect.Constructor;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 对List集合copy
 *
 * @author Durian
 * @date 2023/12/8
 */
public class BeanListUtils extends BeanUtils {

    /**
     * 复制集合的数据到新集合中
     *
     * @param sources 源集合
     * @param clazz 目标集合
     * @return 处理后的集合
     */
    public static <V,P> List<V> copyListUtil(List<P> sources , Class<V> clazz){

        if (ObjectUtils.isEmpty(sources)) {
            return null;
        }

        return sources.stream().map(source -> {
            V v;
            try {
                Constructor<?> constructor = clazz.getDeclaredConstructor();
                v = (V) constructor.newInstance();
                copyProperties(source, v, clazz);
                return v;
            } catch (Exception e) {
                throw new ServiceException(e.getMessage());
            }
        }).collect(Collectors.toList());
    }
}
